package com.gitee.fantaros.web.fan.netcut.threading;

import jakarta.validation.constraints.NotNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamebleThreadFactory implements ThreadFactory {
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup threadGroup;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    public NamebleThreadFactory(String prefix) {
        this.threadGroup = Thread.currentThread().getThreadGroup();
        this.namePrefix = String.format("%1$s-%2$d-thread-", prefix, POOL_NUMBER.getAndIncrement());
    }

    @Override
    public Thread newThread(@NotNull Runnable runnable) {
        Thread childThread = new Thread(threadGroup, runnable, namePrefix + threadNumber.getAndIncrement(), 0);
        if (childThread.isDaemon()) {
            childThread.setDaemon(false);
        }
        if (childThread.getPriority() != Thread.NORM_PRIORITY) {
            childThread.setPriority(Thread.NORM_PRIORITY);
        }
        return childThread;
    }
}
